import { _decorator, Component, Node, Collider2D, Contact2DType, } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerBulletControl')
export class PlayerBulletControl extends Component {
    @property
    speed: number = 200;

    collider: Collider2D = null;
    start() {
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.once(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
    
    onBeginContact(){
        //碰撞检测直接摧毁子弹
        //注意延迟操作到主线程，Box2d碰撞检测期间会锁定物理世界，以防止迭代过程中修改刚体
        //因此在接触监听器(contact listener)中改变刚体状态可能导致问题，因为此时物理世界处于锁定
        if(this.collider){
            this.collider.enabled = false;
        }
        setTimeout(() => {
            this.node.destroy();
        } , 0)
    }

    update(deltaTime: number) {
        const bulletPos = this.node.position;
        let targetposY = bulletPos.y + this.speed * deltaTime;
        this.node.setPosition(bulletPos.x, targetposY, bulletPos.z);
        if (targetposY > 600) {
            this.node.destroy();
        }
    }
    protected onDestroy(): void {
        //摧毁节点时注销碰撞回调
        if(this.collider){
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
}


